clear all
set more off
set maxvar 20000

*Define directory with input data
cd "Q:"

*Consumption analysis

*Start with analysis file
use se_analysis_data_cleaned_1996_2018, clear

*Set survey weights
svyset secu [pw=sswgts_ev_scaled], strata(stratum) singleunit(scaled)

*Intensive margin criteria
gen hhcrit=1 if noimpute==1 & insamp==1 & waveyr>=2004 & waveyr<=2016 & wtcrnh>0 & wtcrnh!=. & (merge_ser_lcy==3 | merge_der_lcy==3) & sswgts_ev_scaled!=. & se_inc2_thou_real_noimp!=. & tot_se_earn_lcy_thou_real!=. & wage_inc2_thou_real!=. & non_se_earn_lcy_thou_real!=. 

*Identify relevant variables
keep hhidc hhidpn hhid pn waveyr hhcrit sswgts_ev_scaled se_inc2_thou_real_noimp tot_se_earn_lcy_thou_real wage_inc2_thou_real non_se_earn_lcy_thou_real itot iotot iftot laborforcestatus age

gen worksft=0
replace worksft=1 if laborforcestatus==1

*Merge in CAMS spending data
merge 1:1 hhidpn waveyr using hrsrandcamsdata_2000_2018
drop if _merge==2
drop _merge

destring hhidpn_string, replace

*Fill in non-merged to 0
local cvars = "cndurf ctotsf cndur ctots cwgthh"
foreach v in `cvars' {
	replace `v'=0 if `v'==.
	}
	
*Aggregate to HH level
collapse (sum) hhcrit sswgts_ev_scaled se_inc2_thou_real_noimp tot_se_earn_lcy_thou_real wage_inc2_thou_real non_se_earn_lcy_thou_real worksft (mean) `cvars' itot iotot iftot (count) hhidpn hhidpn_string (min) min_age=age (max) max_age=age, by(hhidc waveyr)

*Keep only if all HH members and only one consumption record 
keep if hhidpn==hhcrit
drop if hhidpn_string==0

*Regression
gen ln_itot=ln(itot)
gen ln_cndur=ln(cndur)
gen ln_ctots=ln(ctots)
gen taxtot=((tot_se_earn_lcy_thou_real+non_se_earn_lcy_thou_real)+(itot/1000-se_inc2_thou_real_noimp-wage_inc2_thou_real))*1000
gen ln_taxtot=ln(taxtot)

gen hhsizedum=hhidpn-1
gen se_ind=1 if se_inc2_thou_real_noimp>0 & wage_inc2_thou_real==0
replace se_ind=0 if se_inc2_thou_real_noimp==0 & wage_inc2_thou_real>0

reg ln_cndur ln_itot se_ind hhsizedum 
reg ln_ctots ln_itot se_ind hhsizedum 

reg ln_cndur ln_taxtot se_ind hhsizedum 
reg ln_ctots ln_taxtot se_ind hhsizedum 

local outregfile table5
local yvars = "ln_cndur ln_ctots"
local xvars = "ln_itot ln_taxtot"

foreach x in `xvars' {
foreach y in `yvars' {
	reg `y' `x' se_ind hhsizedum
	outreg2 using `outregfile', dec(2) excel
}
}